using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class TreasureChestController : MonoBehaviour
{
    [Header("宝箱设置")]
    public int health = 3; // 宝箱血量
    public PowerUpController.PowerUpType dropType = PowerUpController.PowerUpType.SpreadShot; // 掉落道具类型
    public float moveSpeed = 2f; // 移动速度
    [Tooltip("打掉宝箱后是否立刻把效果赋予玩家（无需拾取）")]
    public bool applyEffectOnDestroy = true;
    [Tooltip("当直接赋予玩家效果时的持续时间（秒）")]
    public float effectDuration = 10f;
    [Tooltip("当直接赋予玩家效果时的强度（>=1。1表示无加成）")]
    public float effectStrength = 1.5f;
    [Tooltip("在直接赋予玩家效果的同时，是否仍然掉落一个仅展示用途的拾取物（不会再次生效）")]
    public bool alsoDropPickup = false;
    [Tooltip("优先使用该预制体作为掉落与效果来源（其 PowerUpController 决定类型/参数）")]
    public GameObject pickupPrefabOverride;
    
    [Header("视觉效果")]
    public Color chestColor = Color.yellow; // 宝箱颜色
    public bool showHealthBar = true; // 显示血量条
    public float flashDuration = 0.15f; // 闪烁持续时间
    public Color hitFlashColor = Color.white; // 击中时的闪烁颜色
    public float scaleOnHit = 1.1f; // 击中时的缩放效果
    
    [Header("调试设置")]
    public bool showDebugInfo = true;
    
    [Header("网格位置")]
    [HideInInspector]
    public int gridRow = -1; // 网格行位置
    [HideInInspector]
    public int gridCol = -1; // 网格列位置
    
    private int maxHealth;
    private SpriteRenderer spriteRenderer;
    private Rigidbody2D rb;
    private GameObject healthDisplay;
    private TextMeshPro healthText;
    private Coroutine hitRoutine; // 受击协程句柄，避免叠加
    private Vector3 baseScale;    // 基准缩放，防止累计
    
    // 使用PowerUpController中的PowerUpType枚举
    
    void Start()
    {
        InitializeChest();
    }
    
    void Update()
    {
        MoveChest();
        
        if (showDebugInfo)
        {
            Debug.Log($"宝箱血量: {health}/{maxHealth}, 位置: {transform.position}");
        }
    }
    
    void InitializeChest()
    {
        maxHealth = health;
        baseScale = transform.localScale;
        
        // 获取组件
        spriteRenderer = GetComponent<SpriteRenderer>();
        rb = GetComponent<Rigidbody2D>();
        
        // 设置视觉效果
        if (spriteRenderer != null)
        {
            spriteRenderer.color = chestColor;
            
            // 添加发光效果
            spriteRenderer.material = CreateGlowMaterial();
        }
        
        // 设置刚体属性
        if (rb != null)
        {
            rb.gravityScale = 0f;
            rb.freezeRotation = true;
        }
        
        // 设置标签
        gameObject.tag = "TreasureChest";
        
        // 创建血量显示
        if (showHealthBar)
        {
            CreateHealthDisplay();
        }
        
        Debug.Log($"宝箱已初始化: 血量={health}, 掉落类型={dropType}");
    }
    
    void MoveChest()
    {
        // 如果宝箱在网格中（gridRow >= 0），则不移动
        if (gridRow >= 0 && gridCol >= 0)
        {
            return; // 网格中的宝箱保持静止
        }
        
        // 只有非网格宝箱才向下移动
        transform.Translate(Vector2.down * moveSpeed * Time.deltaTime);
        
        // 边界检查
        if (BoundaryManager.Instance != null && BoundaryManager.Instance.IsOutOfBounds(transform.position))
        {
            DestroyChest();
        }
    }
    
    void OnTriggerEnter2D(Collider2D other)
    {
        // 检测玩家子弹碰撞
        if (other.CompareTag("PlayerBullet"))
        {
            TakeDamage(1);
            
            // 销毁子弹
            BulletController bullet = other.GetComponent<BulletController>();
            if (bullet != null)
            {
                bullet.DestroyBullet();
            }
            else
            {
                Destroy(other.gameObject);
            }
        }
    }
    
    public void TakeDamage(int damage)
    {
        health -= damage;
        
        // 更新血量显示
        UpdateHealthDisplay();
        
        // 受伤效果
        if (spriteRenderer != null)
        {
            if (hitRoutine != null) StopCoroutine(hitRoutine);
            hitRoutine = StartCoroutine(FlashEffect());
        }
        
        if (showDebugInfo)
        {
            Debug.Log($"宝箱受到伤害: {damage}, 剩余血量: {health}");
        }
        
        // 检查是否被摧毁
        if (health <= 0)
        {
            OpenChest();
        }
    }
    
    System.Collections.IEnumerator FlashEffect()
    {
        Color originalColor = spriteRenderer.color;
        // 每次从基准缩放开始，避免累计
        transform.localScale = baseScale;
        
        // 闪烁和缩放效果
        spriteRenderer.color = hitFlashColor;
        transform.localScale = baseScale * scaleOnHit;
        
        yield return new WaitForSeconds(flashDuration * 0.5f);
        
        // 恢复原状
        spriteRenderer.color = originalColor;
        transform.localScale = baseScale;
        hitRoutine = null;
        
        yield return new WaitForSeconds(flashDuration * 0.5f);
    }
    
    void OpenChest()
    {
        // 直接赋予玩家效果 或 掉落可拾取物
        if (applyEffectOnDestroy)
        {
            var typeToApply = ResolvePowerUpType();
            var (dur, str) = ResolveEffectParams();
            ApplyPowerUpToPlayer(typeToApply, dur, str);
            if (alsoDropPickup)
            {
                DropPowerUp(true); // 仅展示用，不再触发效果
            }
        }
        else
        {
            DropPowerUp(false);
        }
        
        // 播放开箱效果
        CreateOpenEffect();
        
        Debug.Log($"宝箱被打开! 掉落道具类型: {dropType}");
        
        // 销毁宝箱
        DestroyChest();
    }
    
    void DropPowerUp(bool visualOnly)
    {
        // 创建道具掉落
        GameObject powerUpPrefab = GetPowerUpPrefab();
        if (powerUpPrefab != null)
        {
            GameObject powerUp = Instantiate(powerUpPrefab, transform.position, Quaternion.identity);
            
            // 设置道具属性
            PowerUpController powerUpController = powerUp.GetComponent<PowerUpController>();
            if (powerUpController != null)
            {
                // 若没有在预制体上配置，则使用宝箱的 dropType 兜底
                if (powerUpController.powerUpType != dropType)
                {
                    powerUpController.SetPowerUpType(dropType);
                }
                powerUpController.applyOnCollect = !visualOnly;
            }
        }
    }

    void ApplyPowerUpToPlayer(PowerUpController.PowerUpType type, float duration, float strength)
    {
        Debug.Log($"[TreasureChest] 尝试应用道具效果: {type}, 持续时间: {duration}s, 强度: {strength}");
        
        GameObject player = GameObject.FindGameObjectWithTag("Player");
        if (player == null)
        {
            Debug.LogWarning("未找到带有 Player 标签的对象，无法直接应用道具效果。");
            return;
        }
        
        Debug.Log($"[TreasureChest] 找到玩家对象: {player.name}");
        
        var manager = player.GetComponent<PowerUpManager>();
        if (manager == null)
        {
            Debug.Log("[TreasureChest] 玩家没有 PowerUpManager，正在添加...");
            manager = player.AddComponent<PowerUpManager>();
        }
        
        Debug.Log($"[TreasureChest] 调用 PowerUpManager.ApplyPowerUp");
        manager.ApplyPowerUp(type, duration, strength);
        Debug.Log($"[TreasureChest] 道具效果应用完成");
    }
    
    GameObject GetPowerUpPrefab()
    {
        // 优先使用外部指定的覆盖预制体
        if (pickupPrefabOverride != null)
        {
            return pickupPrefabOverride;
        }
        
        GameObject prefab = null;
        switch (dropType)
        {
            case PowerUpController.PowerUpType.SpreadShot:
                prefab = Resources.Load<GameObject>("Prefabs/SpreadShotPowerUp");
                break;
            case PowerUpController.PowerUpType.BurstFire:
                prefab = Resources.Load<GameObject>("Prefabs/BurstFirePowerUp");
                break;
            case PowerUpController.PowerUpType.UpgradedBullet:
                prefab = Resources.Load<GameObject>("Prefabs/UpgradedBullet");
                break;
            case PowerUpController.PowerUpType.BulletUpgradePowerUp:
                prefab = Resources.Load<GameObject>("Prefabs/BulletUpgradePowerUp");
                break;
        }
        
        if (prefab == null)
        {
            Debug.LogWarning($"未在 Resources/Prefabs 下找到 {dropType} 对应的预制体。将使用运行时创建的通用道具。");
            // 兜底：创建一个带 PowerUpController 的通用道具
            GameObject fallback = new GameObject($"{dropType}PowerUp_Runtime");
            var sr = fallback.AddComponent<SpriteRenderer>();
            var puc = fallback.AddComponent<PowerUpController>();
            puc.SetPowerUpType(dropType);
            return fallback;
        }
        
        return prefab;
    }

    PowerUpController.PowerUpType ResolvePowerUpType()
    {
        if (pickupPrefabOverride != null)
        {
            var puc = pickupPrefabOverride.GetComponent<PowerUpController>();
            if (puc != null)
            {
                return puc.powerUpType;
            }
        }
        return dropType;
    }

    (float duration, float strength) ResolveEffectParams()
    {
        if (pickupPrefabOverride != null)
        {
            var puc = pickupPrefabOverride.GetComponent<PowerUpController>();
            if (puc != null)
            {
                return (puc.effectDuration, puc.effectStrength);
            }
        }
        return (effectDuration, effectStrength);
    }
    
    void CreateOpenEffect()
    {
        // 创建粒子特效
        GameObject effect = new GameObject("OpenEffect");
        effect.transform.position = transform.position;
        
        ParticleSystem particles = effect.AddComponent<ParticleSystem>();
        
        var main = particles.main;
        main.startColor = new ParticleSystem.MinMaxGradient(Color.yellow, Color.red);
        main.startSize = new ParticleSystem.MinMaxCurve(0.1f, 0.3f);
        main.startLifetime = 1.5f;
        main.startSpeed = new ParticleSystem.MinMaxCurve(2f, 5f);
        main.maxParticles = 30;
        main.simulationSpace = ParticleSystemSimulationSpace.World;
        
        var emission = particles.emission;
        emission.rateOverTime = 0;
        emission.SetBursts(new ParticleSystem.Burst[]
        {
            new ParticleSystem.Burst(0.0f, 30)
        });
        
        var shape = particles.shape;
        shape.enabled = true;
        shape.shapeType = ParticleSystemShapeType.Circle;
        shape.radius = 0.5f;
        
        var velocityOverLifetime = particles.velocityOverLifetime;
        velocityOverLifetime.enabled = true;
        velocityOverLifetime.space = ParticleSystemSimulationSpace.Local;
        velocityOverLifetime.radial = new ParticleSystem.MinMaxCurve(3f, 6f);
        
        var colorOverLifetime = particles.colorOverLifetime;
        colorOverLifetime.enabled = true;
        Gradient gradient = new Gradient();
        gradient.SetKeys(
            new GradientColorKey[] { new GradientColorKey(Color.yellow, 0.0f), new GradientColorKey(Color.red, 1.0f) },
            new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f), new GradientAlphaKey(0.0f, 1.0f) }
        );
        colorOverLifetime.color = gradient;
        
        // 自动销毁特效
        Destroy(effect, 2f);
    }
    
    void DestroyChest()
    {
        Destroy(gameObject);
    }
    
    void CreateHealthDisplay()
    {
        // 创建血量显示对象
        healthDisplay = new GameObject("HealthDisplay");
        healthDisplay.transform.SetParent(transform);
        healthDisplay.transform.localPosition = new Vector3(0f, 0.6f, 0f);
        
        // 添加TextMeshPro组件
        healthText = healthDisplay.AddComponent<TextMeshPro>();
        healthText.text = health.ToString();
        healthText.fontSize = 2f;
        healthText.color = Color.yellow;
        healthText.alignment = TextAlignmentOptions.Center;
        healthText.sortingOrder = 10; // 确保在最前面显示
        
        // 设置字体样式
        healthText.fontStyle = FontStyles.Bold;
        
        if (showDebugInfo)
        {
            Debug.Log($"创建血量显示: {health}");
        }
    }
    
    void UpdateHealthDisplay()
    {
        if (healthText != null)
        {
            healthText.text = health.ToString();
            
            // 根据血量改变颜色
            if (health <= 1)
            {
                healthText.color = Color.red;
            }
            else if (health <= maxHealth / 2)
            {
                healthText.color = Color.white;
            }
            else
            {
                healthText.color = Color.yellow;
            }
        }
    }

     // 公共方法：设置宝箱属性
    public void SetChestProperties(int hp, PowerUpController.PowerUpType type, float speed = 2f)
    {
        health = hp;
        maxHealth = hp;
        dropType = type;
        moveSpeed = speed;
                    
        // 更新血量显示
        UpdateHealthDisplay();
    }
    
    Material CreateGlowMaterial()
    {
         // 创建一个简单的发光材质
        Material glowMaterial = new Material(Shader.Find("Sprites/Default"));
        glowMaterial.color = chestColor;
        
         // 如果有更高级的着色器，可以在这里设置发光效果
         // 这里使用默认着色器作为基础
        
        return glowMaterial;
    }
 }